<!DOCTYPE html>
<html lang="en">

<!-- Head tag (contains Google-Analytics、Baidu-Tongji)-->
<head>
  <!-- Google Analytics -->
  

  <!-- Baidu Tongji -->
  
    <script type="text/javascript">
      // Originial
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?cdf616a127124dd7ff798963125b304d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  <!-- Baidu Push -->
  
    <script>
      (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
      })();
    </script>
  

  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

  <meta name="google-site-verification" content="lxDfCplOZbIzjhG34NuQBgu2gdyRlAtMB4utP5AgEBc"/>
  <meta name="baidu-site-verification" content="PpzM9WxOJU"/>

  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="description" content="It&#39;s an IT blog..."/>
  <meta name="keyword" content="zhuang,IT  blog,Blog"/>
  <link rel="shortcut icon" href="/img/avatar/java-head.png"/>

  <!-- Place this tag in your head or just before your close body tag. -->
  <script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script>

  
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/beantech.min.css"/>

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css"/>
    <link rel="stylesheet" href="/css/widget.css"/>
    <link rel="stylesheet" href="/css/rocket.css"/>
    <link rel="stylesheet" href="/css/signature.css"/>
    <link rel="stylesheet" href="/css/catalog.css"/>
    <link rel="stylesheet" href="/css/livemylife.css"/>

    
      <!-- wave start -->
      <link rel="stylesheet" href="/css/wave.css"/>
      <!-- wave end -->
    

    
      <!-- top start (article top hot config) -->
      <link rel="stylesheet" href="/css/top.css"/>
      <!-- top end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/scroll.css"/>
      <!-- ThemeColor end -->
    

    
      <!-- viewer start (Picture preview) -->
      <link rel="stylesheet" href="/css/viewer.min.css"/>
      <!-- viewer end -->
    

    
      <!-- Search start -->
      <link rel="stylesheet" href="/css/search.css"/>
      <!-- Search end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/themecolor.css"/>
      <!-- ThemeColor end -->
    

    

    
  

  <!-- Custom Fonts -->
  <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
  <!-- Hux change font-awesome CDN to qiniu -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" type="text/css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <!-- Hux Delete, sad but pending in China <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link
  href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/ css'> -->

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]-->

  <!-- ga & ba script hoook -->
  <link rel="canonical" href="http://yoursite-url/cn/python/文本处理/">
  <title>
    
      python基础 &gt; 文本处理 - either thin | or die
    
  </title>
<meta name="generator" content="Hexo 5.4.0"></head>


<!-- hack iOS CSS :active style -->

	<body ontouchstart="" class="body--light body--dark">


		<!-- ThemeColor -->
		
		<!-- ThemeColor -->
<style type="text/css">
  .body--light {
    --light-mode: none;
    --dark-mode: block;
  }
  .body--dark {
    --light-mode: block;
    --dark-mode: none;
  }
  i.mdui-icon.material-icons.light-mode {
    display: var(--light-mode);
  }
  i.mdui-icon.material-icons.dark-mode {
    display: var(--dark-mode);
  }
</style>
<div class="toggle" onclick="document.body.classList.toggle('body--dark')">
  <i class="mdui-icon material-icons light-mode"></i>
  <i class="mdui-icon material-icons dark-mode"></i>
</div>
<script>
  //getCookieValue
  function getCookieValue(a) {
    var b = document.cookie.match('(^|[^;]+)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b
      ? b.pop()
      : '';
  }
  let themeMode = 'dark';
  if (getCookieValue('sb-color-mode') && (getCookieValue('sb-color-mode') !== themeMode)) {
    let dbody = document.body.classList;
    themeMode === 'dark' ? dbody.remove('body--dark') : dbody.add('body--dark');
  }

  //setCookieValue
  var toggleBtn = document.querySelector(".toggle");
  toggleBtn.addEventListener("click", function () {
    var e = document.body.classList.contains("body--dark");
    var cookieString = e
      ? "dark"
      : "light";
    var exp = new Date();
    exp.setTime(exp.getTime() + 3 * 24 * 60 * 60 * 1000); //3天过期
    document.cookie = "sb-color-mode=" + cookieString + ";expires=" + exp.toGMTString() + ";path=/";
  });
</script>

		

		<!-- Gitter -->
		

		<!-- Navigation (contains search)-->
		<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header page-scroll">
      <button type="button" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">平平淡淡</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <!-- Known Issue, found by Hux: <nav>'s height woule be hold on by its content. so, when navbar scale out, the <nav> will cover tags. also mask any touch event of tags, unfortunately. -->
    <div id="huxblog_navbar">
      <div class="navbar-collapse">
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a href="/">首页</a>
          </li>

          
          
          
          
          <li>
            <a href="/archive/">
              
              归档
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/tags/">
              
              标签
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/categories/">
              
              分类
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/about/">
              
              关于
              
              
            </a>
          </li>
          
          

          
          <li>
            <a class="popup-trigger">
              <span class="search-icon"></span>搜索</a>
          </li>
          

          <!-- LangSelect -->
          
        </ul>
      </div>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container -->
</nav>
<!-- progress -->
<div id="progress">
  <div class="line" style="width: 0%;"></div>
</div>

<script>
  // Drop Bootstarp low-performance Navbar Use customize navbar with high-quality material design animation in high-perf jank-free CSS3 implementation
  var $body = document.body;
  var $toggle = document.querySelector('.navbar-toggle');
  var $navbar = document.querySelector('#huxblog_navbar');
  var $collapse = document.querySelector('.navbar-collapse');

  $toggle.addEventListener('click', handleMagic)

  function handleMagic(e) {
    if ($navbar.className.indexOf('in') > 0) {
      // CLOSE
      $navbar.className = " ";
      // wait until animation end.
      setTimeout(function() {
        // prevent frequently toggle
        if ($navbar.className.indexOf('in') < 0) {
          $collapse.style.height = "0px"
        }
      }, 400)
    } else {
      // OPEN
      $collapse.style.height = "auto"
      $navbar.className += " in";
    }
  }
</script>


		<!-- Post Header (contains intro-header、signature、wordcount、busuanzi、waveoverlay) -->
		<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->

  <style type="text/css">
    .body--light {
      /* intro-header */
      --intro-header-background-image-url-home: url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: url('//img/header_img/lml_bg.jpg');
    }
    .body--dark {
      --intro-header-background-image-url-home: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('//img/header_img/lml_bg.jpg');
    }

    header.intro-header {
       /*post*/
        background-image: var(--intro-header-background-image-url-post);
        /* background-image: url('/img/header_img/lml_bg.jpg'); */
      
    }

    
      #signature {/*signature*/
        background-image: url('/img/signature/signature.png');
      }
    
  </style>





<header class="intro-header">
  <!-- Signature -->
  <div id="signature">
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
          
          <div class="post-heading">
            <div class="tags">
              
              <a class="tag" href="/tags/#python" title="python">python</a>
              
              <a class="tag" href="/tags/#基础" title="基础">基础</a>
              
            </div>
            <h1>python基础 &gt; 文本处理</h1>
            <h2 class="subheading"></h2>
            <span class="meta">
              Posted by zhuang on
              2020-11-26
            </span>


            
            <!-- WordCount start -->
            <div class="blank_box"></div>
            <span class="meta">
              Estimated Reading Time <span class="post-count">14</span> Minutes
            </span>
            <div class="blank_box"></div>
            <span class="meta">
              Words <span class="post-count">3.2k</span> In Total
            </span>
            <div class="blank_box"></div>
            <!-- WordCount end -->
            
            
            <!-- 不蒜子统计 start -->
            <span class="meta" id="busuanzi_container_page_pv">
              Viewed <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Times
            </span>
            <!-- 不蒜子统计 end -->
            


          </div>
          
        </div>
      </div>
    </div>
  </div>

  
  <!-- waveoverlay start -->
  <div class="preview-overlay">
    <svg class="preview-waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
      <defs>
        <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"></path>
      </defs>
      <g class="preview-parallax">
        <use xlink:href="#gentle-wave" x="48" y="0" fill=var(--gentle-wave1)></use>
        <use xlink:href="#gentle-wave" x="48" y="3" fill=var(--gentle-wave2)></use>
        <use xlink:href="#gentle-wave" x="48" y="5" fill=var(--gentle-wave3)></use>
        <use xlink:href="#gentle-wave" x="48" y="7" fill=var(--gentle-wave)></use>
      </g>
    </svg>
  </div>
  <!-- waveoverlay end -->
  

</header>



		<!-- Main Content (Post contains
	Pager、
	tip、
	socialshare、
	gitalk、gitment、disqus-comment、
	Catalog、
	Sidebar、
	Featured-Tags、
	Friends Blog、
	anchorjs、
	) -->
		<!-- Modify by Yu-Hsuan Yen -->
<!-- Post Content -->
<article>
  <div class="container">
    <div class="row">
      <!-- Post Container -->
      <div class="col-lg-8 col-lg-offset-1 col-md-10 col-md-offset-1 post-container">

        <p>字符串不属于<strong>不可变有序</strong>序列，使用单引号、双引号、三单引号或三双引号作为定界符，不同的定界符之间可以互相嵌套。</p>
<ul>
<li>支持序列通用操作(双向索引，比较大小，计算长度，元素访问，切片，成员测试等)</li>
<li>支持特有的用法(字符串格式化，查找，替换，排版等)</li>
<li>不能直接对字符串增、修改与删除等操作</li>
<li>切片操作只能访问元素而不能修改字符</li>
<li>字符串对象提供的<code>replace()</code>和<code>translate()</code>方法以及大量排版方法返回的是一个新字符串</li>
<li>使用<code>isinstance()</code>或<code>type()</code>判断变量是否为字符串</li>
<li>str类型通过<code>encode()</code>指定编码成员bytes对象</li>
<li>bytes对象通过<code>decode()</code>使用正确编码格式解码成str对象</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&#x27;中国&#x27;</span></span><br><span class="line">b = s.encode()   <span class="comment">#默认使用UTF-8进行编码</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(b))       <span class="comment">#&lt;class &#x27;bytes&#x27;&gt;</span></span><br><span class="line"><span class="built_in">print</span>(b)             <span class="comment">#b&#x27;\xe4\xb8\xad\xe5\x9b\xbd&#x27;</span></span><br><span class="line"></span><br><span class="line">e = b.decode(<span class="string">&#x27;UTF-8&#x27;</span>) <span class="comment">#默认使用UTF-8进行解码</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(e))       <span class="comment">#&lt;class &#x27;str&#x27;&gt;</span></span><br><span class="line"><span class="built_in">print</span>(e)             <span class="comment">#中国</span></span><br><span class="line"></span><br><span class="line">b = <span class="built_in">bytes</span>(s,<span class="string">&#x27;gbk&#x27;</span>)  </span><br><span class="line"><span class="built_in">print</span>(b)            <span class="comment">#b&#x27;\xd6\xd0\xb9\xfa&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">str</span>(b,<span class="string">&#x27;gbk&#x27;</span>)) <span class="comment">#中国</span></span><br></pre></td></tr></table></figure>
<h2 id="1-字符串编码格式"><a href="#1-字符串编码格式" class="headerlink" title="1. 字符串编码格式"></a>1. 字符串编码格式</h2><ul>
<li>UTF-8万国编码，以1个字节表示英文，以3个字节表示中文</li>
<li>GB2312我国中文编码，1个字节表示英文，2个字节表示中文</li>
<li>GBK是GB2312的扩充，也是使用2个字节表示中文</li>
</ul>
<h2 id="2-转义字符与原始字符串"><a href="#2-转义字符与原始字符串" class="headerlink" title="2. 转义字符与原始字符串"></a>2. 转义字符与原始字符串</h2><p>转义字符是指，在字符串中某些特定的符号前加一个斜线之后，该字符将解释为另外一种含义。</p>
<ul>
<li>\b：退格，把光标移动前一列位置</li>
<li>\f：换页符</li>
<li>\n：换行符</li>
<li>\r：回车</li>
<li>\t：水平制表符</li>
<li>\v：垂直制表符</li>
<li><code>\&#39;</code>：单引号’</li>
<li><code>\&quot;</code>：双引号“</li>
<li>\ooo：3位八进制对应的字符</li>
<li>\xhh：2位十六进制数对应的字符</li>
<li>\u：4位十六进制数表示的Unicode字符</li>
</ul>
<p><strong><em>在字符串前面加上字母r或R表示原始字符串，其中的所有字符都表示原始的含义而不会进行任何转义</em></strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">path = <span class="string">&#x27;C:\Windows\notepad.exe&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(path)</span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">C:\Windows</span></span><br><span class="line"><span class="string">otepad.exe</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line">path = <span class="string">r&#x27;C:\Windows\notepad.exe&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(path)   <span class="comment">#C:\Windows\notepad.exe</span></span><br></pre></td></tr></table></figure>
<h2 id="3-字符串格式化"><a href="#3-字符串格式化" class="headerlink" title="3. 字符串格式化"></a>3. 字符串格式化</h2><h3 id="3-1-使用-符号进行格式化"><a href="#3-1-使用-符号进行格式化" class="headerlink" title="3.1 使用 % 符号进行格式化"></a>3.1 使用 % 符号进行格式化</h3><p>格式运算符%之前的部分为格式字符串，之后的部分为需要进行格式化的内容。</p>
<blockquote>
<p>‘%   [-]    [+]    [0]    [m]    [.n]    格式字符’   %    x</p>
</blockquote>
<ul>
<li>%：格式表示，表示格式开始</li>
<li>[-] ：指定左对齐输出</li>
<li>[+]：对正数加正号</li>
<li>[0]：指定空位填0</li>
<li>[m]：指定最小宽度</li>
<li>[.n]：指定精度</li>
<li>格式字符：指定类型</li>
<li>%：格式运算符</li>
<li>x：待转换的表达式</li>
</ul>
<p>格式字符：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>格式字符</th>
<th>说明</th>
<th>格式字符</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>%s</td>
<td>字符串，采用str()</td>
<td>%x</td>
<td>十六进制整数</td>
</tr>
<tr>
<td>%r</td>
<td>字符串，采用repr()</td>
<td>%e</td>
<td>指数，基底为e</td>
</tr>
<tr>
<td>%c</td>
<td>单个字符</td>
<td>%E</td>
<td>指数，基底写成E</td>
</tr>
<tr>
<td>%%</td>
<td>字符%</td>
<td>%f，%F</td>
<td>浮点数</td>
</tr>
<tr>
<td>%d</td>
<td>十进制整数</td>
<td>%g</td>
<td>指数e或浮点数</td>
</tr>
<tr>
<td>%i</td>
<td>十进制整数</td>
<td>%G</td>
<td>指数E或浮点数</td>
</tr>
<tr>
<td>%o</td>
<td>八进制整数</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<h3 id="3-2-使用format-方法进行字符串格式化"><a href="#3-2-使用format-方法进行字符串格式化" class="headerlink" title="3.2 使用format()方法进行字符串格式化"></a>3.2 使用format()方法进行字符串格式化</h3><p>使用<code>format()</code>方法，使用位置进行格式化，使用关键参数进行格式化，支持序列解包格式化，支持在数字常量的中间位置使用单个下画线作为分隔符</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;&#123;0:.3f&#125;&#x27;</span>.<span class="built_in">format</span>(<span class="number">1</span> / <span class="number">3</span>))   <span class="comment">#0.333</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;&#123;0:.3%&#125;&#x27;</span>.<span class="built_in">format</span>(<span class="number">1</span> / <span class="number">3</span>))   <span class="comment">#33.333%</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;&#123;0:_&#125;&#x27;</span>.<span class="built_in">format</span>(<span class="number">1000000000</span>))  <span class="comment">#1_000_000_000</span></span><br><span class="line"><span class="comment">#支持关键参数进行格式化  my name is pang,age is 23,and my qq is97</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;my name is &#123;name&#125;,age is &#123;age&#125;,and my qq is&#123;qq&#125;&#x27;</span>.<span class="built_in">format</span>(name=<span class="string">&#x27;pang&#x27;</span>,age=<span class="number">23</span>,qq=<span class="number">97</span>))</span><br><span class="line"></span><br><span class="line">position = (<span class="number">5</span>, <span class="number">8</span>, <span class="number">13</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;X:&#123;0[0]&#125;;Y:&#123;0[1]&#125;;Z:&#123;0[2]&#125;&#x27;</span>.<span class="built_in">format</span>(position))  <span class="comment">#X:5;Y:8;Z:13</span></span><br><span class="line"></span><br><span class="line">weather = [(<span class="string">&#x27;Monday&#x27;</span>,<span class="string">&#x27;rain&#x27;</span>),(<span class="string">&#x27;Tuesday&#x27;</span>,<span class="string">&#x27;sunny&#x27;</span>),</span><br><span class="line">           (<span class="string">&#x27;Wednesday&#x27;</span>,<span class="string">&#x27;sunny&#x27;</span>),(<span class="string">&#x27;Thursday&#x27;</span>,<span class="string">&#x27;rain&#x27;</span>),</span><br><span class="line">           (<span class="string">&#x27;Friday&#x27;</span>,<span class="string">&#x27;cloudy&#x27;</span>)]</span><br><span class="line">formatter = <span class="string">&quot;Weather of &#x27;&#123;0[0]&#125;&#x27; is &#x27;&#123;0[1]&#125;&#x27;&quot;</span>.<span class="built_in">format</span></span><br><span class="line"><span class="keyword">for</span> item <span class="keyword">in</span> <span class="built_in">map</span>(formatter,weather):</span><br><span class="line">    <span class="built_in">print</span>(item)</span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">Weather of &#x27;Monday&#x27; is &#x27;rain&#x27;</span></span><br><span class="line"><span class="string">Weather of &#x27;Tuesday&#x27; is &#x27;sunny&#x27;</span></span><br><span class="line"><span class="string">Weather of &#x27;Wednesday&#x27; is &#x27;sunny&#x27;</span></span><br><span class="line"><span class="string">Weather of &#x27;Thursday&#x27; is &#x27;rain&#x27;</span></span><br><span class="line"><span class="string">Weather of &#x27;Friday&#x27; is &#x27;cloudy&#x27;</span></span><br><span class="line"><span class="string">&#x27;&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>
<h3 id="3-3-格式化的字符串常量"><a href="#3-3-格式化的字符串常量" class="headerlink" title="3.3 格式化的字符串常量"></a>3.3 格式化的字符串常量</h3><p>从Python3.6.x支持一种新的字符串格式化方式，称为Formatted String Literals，与format()方法类似</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">name = <span class="string">&#x27;pang&#x27;</span></span><br><span class="line">age = <span class="number">23</span></span><br><span class="line">qq = <span class="number">97</span></span><br><span class="line"><span class="comment">#My name is pang,age is 23,and my qq is 97</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&#x27;My name is <span class="subst">&#123;name&#125;</span>,age is <span class="subst">&#123;age&#125;</span>,and my qq is <span class="subst">&#123;qq&#125;</span>&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h3 id="3-4-使用Template模板进行格式化"><a href="#3-4-使用Template模板进行格式化" class="headerlink" title="3.4 使用Template模板进行格式化"></a>3.4 使用Template模板进行格式化</h3><p>string提供了用于字符串格式化的模板类<code>Template</code>，用于大量信息的格式化，适用于页面模板内容的替换和格式化</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> string <span class="keyword">import</span> Template</span><br><span class="line">t = Template(<span class="string">&#x27;My name is $&#123;name&#125;,age is $&#123;age&#125;,and my qq is $&#123;qq&#125;&#x27;</span>)</span><br><span class="line">d = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;pang&#x27;</span>,<span class="string">&#x27;age&#x27;</span>:<span class="number">23</span>,<span class="string">&#x27;qq&#x27;</span>:<span class="number">97</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(t.substitute(d))  <span class="comment">#My name is pang,age is 23,and my qq is 97</span></span><br><span class="line">t = Template(<span class="string">&#x27;My name is $name,age is $age,and my qq is $qq&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(t.substitute(d))  <span class="comment">#My name is pang,age is 23,and my qq is 97</span></span><br></pre></td></tr></table></figure>
<h2 id="4-字符串常用操作"><a href="#4-字符串常用操作" class="headerlink" title="4. 字符串常用操作"></a>4. 字符串常用操作</h2><p><strong><em>字符串对象提供的涉及字符串修改的方法都是返回修改后的新字符串，并不对原字符串做任何修改</em></strong></p>
<h3 id="4-1-查找-find-、rfind-、index-、rindex-、count"><a href="#4-1-查找-find-、rfind-、index-、rindex-、count" class="headerlink" title="4.1 查找 find()、rfind()、index()、rindex()、count()"></a>4.1 查找 find()、rfind()、index()、rindex()、count()</h3><div class="table-container">
<table>
<thead>
<tr>
<th>方法</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>find()</td>
<td>从前开始查找一个字符串在另一个字符串指定范围中首次出现的位置，不存在返回-1</td>
</tr>
<tr>
<td>rfind()</td>
<td>从后开始查询一个字符串在另一个字符串指定范围中首次出现的位置，不存在返回-1</td>
</tr>
<tr>
<td>index()</td>
<td>从前开始查找一个字符串在另一个字符串指定范围中首次出现的位置，不存在则抛出异常</td>
</tr>
<tr>
<td>rindex()</td>
<td>从后开始查找一个字符串在另一个字符串指定范围中首次出现的位置，不存在则抛出异常</td>
</tr>
<tr>
<td>count()</td>
<td>返回一个字符串在另一个字符中出现的次数，不存在则返回0</td>
</tr>
</tbody>
</table>
</div>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&quot;apple,peach,banana,peach,pear&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(s.find(<span class="string">&#x27;peach&#x27;</span>))  <span class="comment">#6 返回第一次出现的位置</span></span><br><span class="line"><span class="built_in">print</span>(s.find(<span class="string">&#x27;peach&#x27;</span>,<span class="number">7</span>))  <span class="comment">#19 指定位置开始查找</span></span><br><span class="line"><span class="built_in">print</span>(s.find(<span class="string">&#x27;peach&#x27;</span>,<span class="number">7</span>,<span class="number">20</span>))  <span class="comment">#-1 指定范围进行查找，没有找到则返回-1</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(s.rfind(<span class="string">&#x27;p&#x27;</span>))  <span class="comment">#25 从字符串尾部向前查找</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(s.index(<span class="string">&#x27;pe&#x27;</span>)) <span class="comment">#6</span></span><br><span class="line"><span class="comment">#print(s.index(&#x27;ssss&#x27;))  #ValueError: substring not found</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(s.count(<span class="string">&#x27;p&#x27;</span>))  <span class="comment">#5</span></span><br></pre></td></tr></table></figure>
<h3 id="4-2-切割-split-、rsplit-、partition-、rpartition"><a href="#4-2-切割-split-、rsplit-、partition-、rpartition" class="headerlink" title="4.2 切割 split()、rsplit()、partition()、rpartition()"></a>4.2 切割 split()、rsplit()、partition()、rpartition()</h3><ul>
<li><p>split()、rsplit()：用来以指定字符为分隔符，从字符串左端和右端开始将其分隔成多个字符串，并返回包含分隔结果的列表。</p>
<ul>
<li>不指定分隔符，则字符串中的任何空白符号的连续出现都将被认为是分隔符</li>
<li>允许指定最大的分隔次数</li>
</ul>
</li>
<li><p>partition()、rpartition()：以指定字符串为分隔符将原字符串分隔为3部分，即分隔符之前的字符串，分隔符字符串和分隔符之后的字符串,并返回包含分隔结果的元组。</p>
<ul>
<li>如果指定的分隔符不在原字符串，则返回原字符串和两个空白字符串</li>
<li>如果字符串中有多个分隔符，partition()从左往右遇到第一个分隔符做为分隔符，rpartition()从右往左</li>
</ul>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&quot;apple,peach,banana,peach,pear&quot;</span></span><br><span class="line"><span class="built_in">print</span>(s.split(<span class="string">&#x27;,&#x27;</span>))  <span class="comment">#[&#x27;apple&#x27;, &#x27;peach&#x27;, &#x27;banana&#x27;, &#x27;peach&#x27;, &#x27;pear&#x27;]</span></span><br><span class="line"></span><br><span class="line">s = <span class="string">&#x27;2020-11-30&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(s.split(<span class="string">&#x27;-&#x27;</span>)) <span class="comment">#[&#x27;2020&#x27;, &#x27;11&#x27;, &#x27;30&#x27;]</span></span><br><span class="line"></span><br><span class="line">s = <span class="string">&#x27;hello world \n\n\n My name    is pang.&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(s.split())  <span class="comment">#[&#x27;hello&#x27;, &#x27;world&#x27;, &#x27;My&#x27;, &#x27;name&#x27;, &#x27;is&#x27;, &#x27;pang.&#x27;]</span></span><br><span class="line"></span><br><span class="line">s = <span class="string">&#x27;\n\t\thello world \n\n\n My name    is pang.&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(s.split(maxsplit=<span class="number">1</span>))  <span class="comment">#[&#x27;hello&#x27;, &#x27;world \n\n\n My name    is pang.&#x27;]</span></span><br><span class="line"></span><br><span class="line">s = <span class="string">&#x27;\n\t\thello world \n\n\n My name    is pang.&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(s.rsplit(maxsplit=<span class="number">2</span>))  <span class="comment">#[&#x27;\n\t\thello world \n\n\n My name&#x27;, &#x27;is&#x27;, &#x27;pang.&#x27;]</span></span><br><span class="line"></span><br><span class="line">s = <span class="string">&quot;apple,peach,banana,peach,pear&quot;</span></span><br><span class="line"><span class="built_in">print</span>(s.partition(<span class="string">&#x27;,&#x27;</span>)) <span class="comment">#(&#x27;apple&#x27;, &#x27;,&#x27;, &#x27;peach,banana,peach,pear&#x27;)</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(s.rpartition(<span class="string">&#x27;,&#x27;</span>)) <span class="comment">#(&#x27;apple,peach,banana,peach&#x27;, &#x27;,&#x27;, &#x27;pear&#x27;)</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(s.partition(<span class="string">&#x27;banana&#x27;</span>)) <span class="comment">#(&#x27;apple,peach,&#x27;, &#x27;banana&#x27;, &#x27;,peach,pear&#x27;)</span></span><br></pre></td></tr></table></figure>
<h3 id="4-3-连接-join"><a href="#4-3-连接-join" class="headerlink" title="4.3 连接 join()"></a>4.3 连接 join()</h3><p>字符串的<code>join()</code>方法用来将列表中多个字符串进行拼接，并在相邻两个字符串之间插入指定字符，返回新字符串。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">s = [<span class="string">&#x27;apple&#x27;</span>, <span class="string">&#x27;peach&#x27;</span>, <span class="string">&#x27;banana&#x27;</span>, <span class="string">&#x27;peach&#x27;</span>, <span class="string">&#x27;pear&#x27;</span>]</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;,&#x27;</span>.join(s))  <span class="comment">#apple,peach,banana,peach,pear</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;-&#x27;</span>.join(s))  <span class="comment">#apple-peach-banana-peach-pear</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&#x27;&#x27;</span>.join(s))  <span class="comment">#applepeachbananapeachpear</span></span><br></pre></td></tr></table></figure>
<h3 id="4-4-大小写转换-lower-、upper-、capitalize-、title-、swapcase"><a href="#4-4-大小写转换-lower-、upper-、capitalize-、title-、swapcase" class="headerlink" title="4.4 大小写转换 lower()、upper()、capitalize()、title()、swapcase()"></a>4.4 大小写转换 lower()、upper()、capitalize()、title()、swapcase()</h3><ul>
<li>lower()：将字符串转换为小写</li>
<li>upper()：将字符串装换为大写</li>
<li>capitalize()：将字符串首字母变为大写</li>
<li>title()：将每个单词的首字母变为大写</li>
<li>swapcase()：大写以及小写互换</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&quot;What is Your Name?&quot;</span></span><br><span class="line"><span class="built_in">print</span>(s.lower())   <span class="comment">#what is your name?</span></span><br><span class="line"><span class="built_in">print</span>(s.upper())   <span class="comment">#WHAT IS YOUR NAME?</span></span><br><span class="line"><span class="built_in">print</span>(s.capitalize()) <span class="comment">#What is your name?</span></span><br><span class="line"><span class="built_in">print</span>(s.title())    <span class="comment">#What Is Your Name?</span></span><br><span class="line"><span class="built_in">print</span>(s.swapcase()) <span class="comment">#wHAT IS yOUR nAME?</span></span><br></pre></td></tr></table></figure>
<h3 id="4-5-替换-replace-、maketrans-、translate"><a href="#4-5-替换-replace-、maketrans-、translate" class="headerlink" title="4.5 替换 replace()、maketrans()、translate()"></a>4.5 替换 replace()、maketrans()、translate()</h3><ul>
<li><code>replace()</code>：用来替换字符串中指定字符或子字符串的所有重复出现，每次只能替换一个字符或一个字符串。</li>
<li><code>maketrans()</code>方法用来生成字符映射表，而<code>translate()</code>方法用来根据映射表对应关系替换其中的字符</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&quot;apple,peach,banana,peach,pear&quot;</span></span><br><span class="line"><span class="built_in">print</span>(s.replace(<span class="string">&#x27;peach&#x27;</span>,<span class="string">&#x27;banana&#x27;</span>))  <span class="comment">#apple,banana,banana,banana,pear</span></span><br><span class="line"></span><br><span class="line">table = <span class="string">&#x27;&#x27;</span>.maketrans(<span class="string">&#x27;abcd&#x27;</span>,<span class="string">&#x27;1234&#x27;</span>)</span><br><span class="line"><span class="built_in">print</span>(table)  <span class="comment">#&#123;97: 49, 98: 50, 99: 51, 100: 52&#125;</span></span><br><span class="line"><span class="built_in">print</span>(s.translate(table))     <span class="comment">#1pple,pe13h,21n1n1,pe13h,pe1r</span></span><br></pre></td></tr></table></figure>
<p>实现凯撒加密算法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> string</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">kaisa</span>(<span class="params">s,k</span>):</span></span><br><span class="line">    lower = string.ascii_lowercase</span><br><span class="line">    upper = string.ascii_uppercase</span><br><span class="line">    before = string.ascii_letters</span><br><span class="line">    after = lower[k:] + lower[:k] + upper[k:] + upper[:k]</span><br><span class="line">    table = <span class="string">&#x27;&#x27;</span>.maketrans(before,after)</span><br><span class="line">    <span class="keyword">return</span> s.translate(table)</span><br><span class="line"><span class="built_in">print</span>(kaisa(s,<span class="number">3</span>))   <span class="comment">#dssoh,shdfk,edqdqd,shdfk,shdu</span></span><br></pre></td></tr></table></figure>
<h3 id="4-6-删除空格-strip-、rstrip-、lstrip"><a href="#4-6-删除空格-strip-、rstrip-、lstrip" class="headerlink" title="4.6 删除空格 strip()、rstrip()、lstrip()"></a>4.6 删除空格 strip()、rstrip()、lstrip()</h3><p>分别用来删除两端、右端、左端连续的空白字符或指定字符。</p>
<ul>
<li>这3个函数的参数指定的字符并不作为一个整体对待，而是在原字符串的两侧、右侧、左侧删除参数字符串中包含的所有字符，一层一层地从外往里扒。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(<span class="string">&quot;   abc   &quot;</span>.strip())         <span class="comment">#abc</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;aaabbbccc&quot;</span>.strip(<span class="string">&quot;a&quot;</span>))      <span class="comment">#bbbccc</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;aaabbbccc&quot;</span>.strip(<span class="string">&quot;ac&quot;</span>))     <span class="comment">#bbb</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;aaabbbcccaaa&quot;</span>.rstrip(<span class="string">&quot;a&quot;</span>))  <span class="comment">#aaabbbccc</span></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;aaabbbcccaaa&quot;</span>.lstrip(<span class="string">&quot;a&quot;</span>))  <span class="comment">#bbbcccaaa</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;aabbccddeeffgg&quot;</span>.strip(<span class="string">&quot;gaef&quot;</span>))  <span class="comment">#bbccdd</span></span><br></pre></td></tr></table></figure>
<h3 id="4-7-stratswith-、endswitch"><a href="#4-7-stratswith-、endswitch" class="headerlink" title="4. 7 stratswith()、endswitch()"></a>4. 7 stratswith()、endswitch()</h3><p>用来判断字符串是否以指定字符串开始或结束，可以接收两个整数参数来限定字符串的检测范围。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">s = <span class="string">&#x27;Beautiful is better than ugly.&#x27;</span></span><br><span class="line"><span class="built_in">print</span>(s.startswith(<span class="string">&#x27;Be&#x27;</span>))      <span class="comment">#True</span></span><br><span class="line"><span class="built_in">print</span>(s.startswith(<span class="string">&#x27;Be&#x27;</span>,<span class="number">4</span>))    <span class="comment">#False</span></span><br><span class="line"><span class="built_in">print</span>(s.startswith(<span class="string">&#x27;Be&#x27;</span>,<span class="number">0</span>,<span class="number">5</span>))  <span class="comment">#True</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line">filename = [filename <span class="keyword">for</span> filename <span class="keyword">in</span> os.listdir(<span class="string">r&quot;F:\\&quot;</span>) <span class="keyword">if</span> filename.endswith((<span class="string">&#x27;.txt&#x27;</span>,<span class="string">&#x27;.gif&#x27;</span>))]</span><br><span class="line"><span class="built_in">print</span>(filename)</span><br></pre></td></tr></table></figure>
<h3 id="4-8-测试字符串属于什么类型（数字、字母、大写字母、小写字母、空白字符）"><a href="#4-8-测试字符串属于什么类型（数字、字母、大写字母、小写字母、空白字符）" class="headerlink" title="4.8 测试字符串属于什么类型（数字、字母、大写字母、小写字母、空白字符）"></a>4.8 测试字符串属于什么类型（数字、字母、大写字母、小写字母、空白字符）</h3><ul>
<li><code>isalnum()</code>：测试字符串是否为数字或字母</li>
<li><code>isalpha()</code>：是否为字母</li>
<li><code>isdigit()</code>：是否为数字</li>
<li><code>isdecimal()</code>：</li>
<li><code>isnumeric()</code>：是否为数字，支持罗马数字，支持汉字数字</li>
<li><code>isspace()</code>：是否为空白字符</li>
<li><code>isupper()</code>：是否为大写</li>
<li><code>islower()</code>：是否为小写</li>
</ul>
<h3 id="4-9-字符串排版-center-、ljust-、rjust-、zfill"><a href="#4-9-字符串排版-center-、ljust-、rjust-、zfill" class="headerlink" title="4.9 字符串排版 center()、ljust() 、rjust()、zfill()"></a>4.9 字符串排版 center()、ljust() 、rjust()、zfill()</h3><p>center()、ljust() 、rjust()返回指定宽度的新字符串，原字符串居中、左对齐或右对齐，则使用指定的字符（默认的是空格）进行填充；</p>
<p>zfill()返回指定宽度的字符串，从左侧以字符0进行填充</p>
<h3 id="4-10-字符串对象支持的运算符"><a href="#4-10-字符串对象支持的运算符" class="headerlink" title="4.10 字符串对象支持的运算符"></a>4.10 字符串对象支持的运算符</h3><p>Python支持使用运算符”+”连接字符串，该运算符涉及大量数据的复制，效率非常低，不适合大量长字符串的连接，推荐使用字符串对象join()</p>
<h3 id="4-11-适用于字符串对象的内置函数"><a href="#4-11-适用于字符串对象的内置函数" class="headerlink" title="4.11 适用于字符串对象的内置函数"></a>4.11 适用于字符串对象的内置函数</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">strItem = <span class="string">&quot;Hello World!&quot;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">len</span>(strItem))   <span class="comment">#12</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">max</span>(strItem))   <span class="comment">#r</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">min</span>(strItem))   <span class="comment">#&#x27; &#x27;</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">zip</span>(strItem,<span class="built_in">range</span>(<span class="built_in">len</span>(strItem)))))</span><br><span class="line"><span class="comment">#[(&#x27;H&#x27;, 0), (&#x27;e&#x27;, 1), (&#x27;l&#x27;, 2), (&#x27;l&#x27;, 3), (&#x27;o&#x27;, 4), (&#x27; &#x27;, 5), (&#x27;W&#x27;, 6), (&#x27;o&#x27;, 7), (&#x27;r&#x27;, 8), (&#x27;l&#x27;, 9), (&#x27;d&#x27;, 10), (&#x27;!&#x27;, 11)]</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">sorted</span>(strItem,reverse=<span class="literal">True</span>))</span><br><span class="line"><span class="comment">#[&#x27;r&#x27;, &#x27;o&#x27;, &#x27;o&#x27;, &#x27;l&#x27;, &#x27;l&#x27;, &#x27;l&#x27;, &#x27;e&#x27;, &#x27;d&#x27;, &#x27;W&#x27;, &#x27;H&#x27;, &#x27;!&#x27;, &#x27; &#x27;]</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">enumerate</span>(strItem)))</span><br><span class="line"><span class="comment">#[(0, &#x27;H&#x27;), (1, &#x27;e&#x27;), (2, &#x27;l&#x27;), (3, &#x27;l&#x27;), (4, &#x27;o&#x27;), (5, &#x27; &#x27;), (6, &#x27;W&#x27;), (7, &#x27;o&#x27;), (8, &#x27;r&#x27;), (9, &#x27;l&#x27;), (10, &#x27;d&#x27;), (11, &#x27;!&#x27;)]</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(<span class="built_in">map</span>(<span class="keyword">lambda</span> i,j: i + j,strItem,strItem)))</span><br><span class="line"><span class="comment">#[&#x27;HH&#x27;, &#x27;ee&#x27;, &#x27;ll&#x27;, &#x27;ll&#x27;, &#x27;oo&#x27;, &#x27;  &#x27;, &#x27;WW&#x27;, &#x27;oo&#x27;, &#x27;rr&#x27;, &#x27;ll&#x27;, &#x27;dd&#x27;, &#x27;!!&#x27;]</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">eval</span>(<span class="string">&quot;3 + 4&quot;</span>))   <span class="comment">#7</span></span><br><span class="line"><span class="keyword">import</span> math</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">eval</span>(<span class="string">&quot;math.sqrt(4)&quot;</span>))  <span class="comment">#2.0</span></span><br></pre></td></tr></table></figure>
<h3 id="4-12-字符串对象的切片操作"><a href="#4-12-字符串对象的切片操作" class="headerlink" title="4. 12 字符串对象的切片操作"></a>4. 12 字符串对象的切片操作</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span>(strItem[:<span class="number">5</span>])  <span class="comment">#Hello</span></span><br><span class="line"><span class="built_in">print</span>(strItem[<span class="number">6</span>:<span class="number">11</span>])  <span class="comment">#World</span></span><br></pre></td></tr></table></figure>
<h2 id="5-字符串常量"><a href="#5-字符串常量" class="headerlink" title="5. 字符串常量"></a>5. 字符串常量</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> string,random</span><br><span class="line">x = string.ascii_letters + string.digits + string.punctuation</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">generateStrongPwd</span>(<span class="params"><span class="built_in">len</span></span>):</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;&#x27;</span>.join((random.choice(x) <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>)))</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(generateStrongPwd(<span class="number">8</span>))   <span class="comment">#&lt;@+BVGWe</span></span><br></pre></td></tr></table></figure>

        <hr>
        <!-- Pager -->
        <ul class="pager">
          
          <li class="previous">
            <a href="/cn/python/数据永久化/" data-toggle="tooltip" data-placement="top" title="python基础 > 数据永久化">&larr; Previous Post</a>
          </li>
          
          
          <li class="next">
            <a href="/cn/python/面向对象程序设计/" data-toggle="tooltip" data-placement="top" title="python基础 > 面向对象程序设计">Next Post &rarr;</a>
          </li>
          
        </ul>

        
        <!-- tip start -->
        <!-- tip -->
<!-- tip start -->
<div class="tip">
  <p>
    
      如果您喜欢此博客或发现它对您有用，则欢迎对此发表评论。 也欢迎您共享此博客，以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权，请与作者联系以将其删除。 谢谢 ！
    
  </p>
</div>
<!-- tip end -->

        <!-- tip end -->
        

        
        <hr>

        <!-- comments start -->
        <!-- 1. gitalk comment -->


<!-- 2. gitment comment -->


<!-- 3. disqus comment -->


        <!-- comments end -->
        <hr>

      </div>

      <!-- Catalog: Tabe of Content -->
      <!-- Table of Contents -->

    
      <aside id="sidebar">
        <div id="toc" class="toc-article">
        <strong class="toc-title">目录</strong>
        
          <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%BC%96%E7%A0%81%E6%A0%BC%E5%BC%8F"><span class="toc-nav-number">1.</span> <span class="toc-nav-text">1. 字符串编码格式</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-%E8%BD%AC%E4%B9%89%E5%AD%97%E7%AC%A6%E4%B8%8E%E5%8E%9F%E5%A7%8B%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="toc-nav-number">2.</span> <span class="toc-nav-text">2. 转义字符与原始字符串</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-nav-number">3.</span> <span class="toc-nav-text">3. 字符串格式化</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-1-%E4%BD%BF%E7%94%A8-%E7%AC%A6%E5%8F%B7%E8%BF%9B%E8%A1%8C%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-nav-number">3.1.</span> <span class="toc-nav-text">3.1 使用 % 符号进行格式化</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-%E4%BD%BF%E7%94%A8format-%E6%96%B9%E6%B3%95%E8%BF%9B%E8%A1%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-nav-number">3.2.</span> <span class="toc-nav-text">3.2 使用format()方法进行字符串格式化</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-3-%E6%A0%BC%E5%BC%8F%E5%8C%96%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B8%B8%E9%87%8F"><span class="toc-nav-number">3.3.</span> <span class="toc-nav-text">3.3 格式化的字符串常量</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-4-%E4%BD%BF%E7%94%A8Template%E6%A8%A1%E6%9D%BF%E8%BF%9B%E8%A1%8C%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="toc-nav-number">3.4.</span> <span class="toc-nav-text">3.4 使用Template模板进行格式化</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C"><span class="toc-nav-number">4.</span> <span class="toc-nav-text">4. 字符串常用操作</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-1-%E6%9F%A5%E6%89%BE-find-%E3%80%81rfind-%E3%80%81index-%E3%80%81rindex-%E3%80%81count"><span class="toc-nav-number">4.1.</span> <span class="toc-nav-text">4.1 查找 find()、rfind()、index()、rindex()、count()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-2-%E5%88%87%E5%89%B2-split-%E3%80%81rsplit-%E3%80%81partition-%E3%80%81rpartition"><span class="toc-nav-number">4.2.</span> <span class="toc-nav-text">4.2 切割 split()、rsplit()、partition()、rpartition()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-3-%E8%BF%9E%E6%8E%A5-join"><span class="toc-nav-number">4.3.</span> <span class="toc-nav-text">4.3 连接 join()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-4-%E5%A4%A7%E5%B0%8F%E5%86%99%E8%BD%AC%E6%8D%A2-lower-%E3%80%81upper-%E3%80%81capitalize-%E3%80%81title-%E3%80%81swapcase"><span class="toc-nav-number">4.4.</span> <span class="toc-nav-text">4.4 大小写转换 lower()、upper()、capitalize()、title()、swapcase()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-5-%E6%9B%BF%E6%8D%A2-replace-%E3%80%81maketrans-%E3%80%81translate"><span class="toc-nav-number">4.5.</span> <span class="toc-nav-text">4.5 替换 replace()、maketrans()、translate()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-6-%E5%88%A0%E9%99%A4%E7%A9%BA%E6%A0%BC-strip-%E3%80%81rstrip-%E3%80%81lstrip"><span class="toc-nav-number">4.6.</span> <span class="toc-nav-text">4.6 删除空格 strip()、rstrip()、lstrip()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-7-stratswith-%E3%80%81endswitch"><span class="toc-nav-number">4.7.</span> <span class="toc-nav-text">4. 7 stratswith()、endswitch()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-8-%E6%B5%8B%E8%AF%95%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B1%9E%E4%BA%8E%E4%BB%80%E4%B9%88%E7%B1%BB%E5%9E%8B%EF%BC%88%E6%95%B0%E5%AD%97%E3%80%81%E5%AD%97%E6%AF%8D%E3%80%81%E5%A4%A7%E5%86%99%E5%AD%97%E6%AF%8D%E3%80%81%E5%B0%8F%E5%86%99%E5%AD%97%E6%AF%8D%E3%80%81%E7%A9%BA%E7%99%BD%E5%AD%97%E7%AC%A6%EF%BC%89"><span class="toc-nav-number">4.8.</span> <span class="toc-nav-text">4.8 测试字符串属于什么类型（数字、字母、大写字母、小写字母、空白字符）</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-9-%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%8E%92%E7%89%88-center-%E3%80%81ljust-%E3%80%81rjust-%E3%80%81zfill"><span class="toc-nav-number">4.9.</span> <span class="toc-nav-text">4.9 字符串排版 center()、ljust() 、rjust()、zfill()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-10-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%AF%B9%E8%B1%A1%E6%94%AF%E6%8C%81%E7%9A%84%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-nav-number">4.10.</span> <span class="toc-nav-text">4.10 字符串对象支持的运算符</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-11-%E9%80%82%E7%94%A8%E4%BA%8E%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0"><span class="toc-nav-number">4.11.</span> <span class="toc-nav-text">4.11 适用于字符串对象的内置函数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-12-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%88%87%E7%89%87%E6%93%8D%E4%BD%9C"><span class="toc-nav-number">4.12.</span> <span class="toc-nav-text">4. 12 字符串对象的切片操作</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#5-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B8%B8%E9%87%8F"><span class="toc-nav-number">5.</span> <span class="toc-nav-text">5. 字符串常量</span></a></li></ol>
        
        </div>
      </aside>
    



      <!-- Sidebar Container -->
      <div class="
                col-lg-8 col-lg-offset-1
                col-md-10 col-md-offset-1
                sidebar-container">

        <!-- Featured Tags -->
        
        <section>
          <!-- no hr -->
          <h5>
            <a href="/tags/">特色标签</a>
          </h5>
          <div class="tags">
            
            <a class="tag" href="/tags/#python" title="python">python</a>
            
            <a class="tag" href="/tags/#基础" title="基础">基础</a>
            
          </div>
        </section>
        

        <!-- Friends Blog -->
        
        <hr>
        <h5>链友</h5>
        <ul class="list-inline">

          
        </ul>
        
      </div>
    </div>
  </div>
</article>



<!-- anchorjs start -->
<!-- async load function -->
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script type="text/javascript">
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function(e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  };
</script>
<script type="text/javascript">
  //anchor-js, Doc:http://bryanbraun.github.io/anchorjs/
  async ("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js", function() {
    anchors.options = {
      visible: 'hover',
      placement: 'left',
      // icon: 'ℬ'
      icon: '❡'
    };
    anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
  });
</script>
<style>
  /* place left on bigger screen */
  @media all and (min-width: 800px) {
    .anchorjs-link {
      position: absolute;
      left: -0.75em;
      font-size: 1.1em;
      margin-top: -0.1em;
    }
  }
</style>

<!-- anchorjs end -->



		<!-- Footer (contains ThemeColor、viewer) -->
		<!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center">
          

          

          

          

          

          

          

          

        </ul>
        <p class="copyright text-muted">
          Copyright &copy;
          zhuang
          2021
          <br>
          Theme by
          <a target="_blank" rel="noopener" href="http://beantech.org">BeanTech</a>
          <span style="display: inline-block; margin: 0 5px;">
            <i class="fa fa-heart"></i>
          </span>
          re-Ported by
          <a target="_blank" rel="noopener" href="https://v-vincen.life/">Live My Life</a>
        </p>
      </div>
    </div>
  </div>
</footer>

<a id="rocket" href="#top" class=""></a>


  <!-- jQuery -->
  <script type="text/javascript" src="/js/jquery.min.js"></script>
  <!-- Bootstrap Core JavaScript -->
  <script type="text/javascript" src="/js/bootstrap.min.js"></script>
  <!-- Custom Theme JavaScript -->
  <script type="text/javascript" src="/js/hux-blog.min.js"></script>
  <!-- catalog -->
  <script async="true" type="text/javascript" src="/js/catalog.js"></script>
  <!-- totop(rocket) -->
  <script async="true" type="text/javascript" src="/js/totop.js"></script>

  
    <!-- Busuanzi JavaScript -->
    <script async="async" src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  

  
    <!-- Scroll start -->
    <script async="async" type="text/javascript" src="/js/scroll.js"></script>
    <!-- Scroll end -->
  

  

  

  
    <!-- ribbon -->
    <script type="text/javascript" src="/js/ribbonDynamic.js"></script>
  

  






  <!-- viewer start -->
  <!-- viewer start (Picture preview) -->
  
    <script async="async" type="text/javascript" src="/js/viewer/viewer.min.js"></script>
    <script async="async" type="text/javascript" src="/js/viewer/pic-viewer.js"></script>
  

  <!-- viewer end -->


<script>
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }

  // fastClick.js
  async ("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
    var $nav = document.querySelector("nav");
    if ($nav)
      FastClick.attach($nav);
    }
  )
</script>

<!-- Because of the native support for backtick-style fenced code blocks right within the Markdown is landed in Github Pages, From V1.6, There is no need for Highlight.js, so Huxblog drops it officially. -
https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0 - https://help.github.com/articles/creating-and-highlighting-code-blocks/ -->
<!-- <script> async ("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function () { hljs.initHighlightingOnLoad(); }) </script> <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet"> -->

<!-- jquery.tagcloud.js -->
<!-- <script> // only load tagcloud.js in tag.html if ($('#tag_cloud').length !== 0) { async ("http://yoursite-url/js/jquery.tagcloud.js", function () { $.fn.tagcloud.defaults = { // size: { start: 1, end: 1, unit: 'em' }, color: {
start: '#bbbbee', end: '#0085a1' } }; $('#tag_cloud a').tagcloud(); }) } </script> -->


		<!-- Search -->
		
		<div class="popup search-popup local-search-popup">
  <span class="popup-btn-close">
    ESC
  </span>
  <div class="container">
    <div class="row">
      <!-- <div class="col-md-9 col-md-offset-1"> -->
      <div class="col-lg-9 col-lg-offset-1 col-md-10 col-md-offset-1 local-search-content">

        <div class="local-search-header clearfix">

          <div class="local-search-input-wrapper">
            <span class="search-icon">
              <i class="fa fa-search fa-lg" style="margin: 25px 10px 25px 20px;"></i>
            </span>
            <input autocomplete="off" placeholder="搜索..." type="text" id="local-search-input">
          </div>
        </div>
        <div id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>


  
    <script src="/js/ziploader.js"></script>
  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    // monitor main search box;
    var onPopupClose = function (e) {
      $('.popup').fadeOut(300);
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $('.popup').fadeIn(300);
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // get search zip version
    $.get('/searchVersion.json?t=' + (+new Date()), function (res) {
      if (localStorage.getItem('searchVersion') !== res) {
        localStorage.setItem('searchVersion', res);
        initSearchJson();
      }
    });

    function initSearchJson() {
      initLoad(['/search.flv'], {
        loadOptions: {
          success: function (obj) {
            localStorage.setItem('searchJson', obj['search.json'])
          },
          error: function (e) {
            return console.log(e)
          }
        },
        returnOptions: {
          'json': TYPE_TEXT
        },
        mimeOptions: {
          'json': 'application/json'
        }
      })
    }
    // search function;
    var searchFunc = function (search_id, content_id) {
      'use strict';
      isfetched = true;
      var datas = JSON.parse(localStorage.getItem('searchJson'));
      // console.log(search_id)
      var input = document.getElementById(search_id);
      var resultContent = document.getElementById(content_id);
      var inputEventFunction = function () {
        var searchText = input.value.trim().toLowerCase();
        var keywords = searchText.split(/[\s\-]+/);
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        var resultItems = [];
        if (searchText.length > 0) {
          // perform local searching
          datas.forEach(function (data) {
            var isMatch = false;
            var hitCount = 0;
            var searchTextCount = 0;
            var title = data.title
              ? data.title.trim()
              : '';
            var titleInLowerCase = title.toLowerCase();
            var content = data.content
              ? data.content.trim().replace(/<[^>]+>/g, "")
              : '';
            var contentInLowerCase = content.toLowerCase();
            var articleUrl = decodeURIComponent(data.url);

            var date = data.date;
            var dateTime = date.replace(/T/, " ").replace(/.000Z/, "");
            var imgUrl = data.header_img;
            


            var indexOfTitle = [];
            var indexOfContent = [];
            // only match articles with not empty titles
            keywords.forEach(function (keyword) {
              function getIndexByWord(word, text, caseSensitive) {
                var wordLen = word.length;
                if (wordLen === 0) {
                  return [];
                }
                var startPosition = 0,
                  position = [],
                  index = [];
                if (!caseSensitive) {
                  text = text.toLowerCase();
                  word = word.toLowerCase();
                }
                while ((position = text.indexOf(word, startPosition)) > -1) {
                  index.push({position: position, word: word});
                  startPosition = position + wordLen;
                }
                return index;
              }
              indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
              indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
            });
            if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
              isMatch = true;
              hitCount = indexOfTitle.length + indexOfContent.length;
            }
            // show search results
            if (isMatch) {
              // sort index by position of keyword
              [indexOfTitle, indexOfContent].forEach(function (index) {
                index.sort(function (itemLeft, itemRight) {
                  if (itemRight.position !== itemLeft.position) {
                    return itemRight.position - itemLeft.position;
                  } else {
                    return itemLeft.word.length - itemRight.word.length;
                  }
                });
              });
              // merge hits into slices
              function mergeIntoSlice(text, start, end, index) {
                var item = index[index.length - 1];
                var position = item.position;
                var word = item.word;
                var hits = [];
                var searchTextCountInSlice = 0;
                while (position + word.length <= end && index.length != 0) {
                  if (word === searchText) {
                    searchTextCountInSlice++;
                  }
                  hits.push({position: position, length: word.length});
                  var wordEnd = position + word.length;
                  // move to next position of hit
                  index.pop();
                  while (index.length != 0) {
                    item = index[index.length - 1];
                    position = item.position;
                    word = item.word;
                    if (wordEnd > position) {
                      index.pop();
                    } else {
                      break;
                    }
                  }
                }
                searchTextCount += searchTextCountInSlice;
                return {hits: hits, start: start, end: end, searchTextCount: searchTextCountInSlice};
              }
              var slicesOfTitle = [];
              if (indexOfTitle.length != 0) {
                slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
              }
              var slicesOfContent = [];
              while (indexOfContent.length != 0) {
                var item = indexOfContent[indexOfContent.length - 1];
                var position = item.position;
                var word = item.word;
                // cut out 100 characters
                var start = position - 20;
                var end = position + 80;
                if (start < 0) {
                  start = 0;
                }
                if (end < position + word.length) {
                  end = position + word.length;
                }
                if (end > content.length) {
                  end = content.length;
                }
                slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
              }
              // sort slices in content by search text's count and hits' count
              slicesOfContent.sort(function (sliceLeft, sliceRight) {
                if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                  return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                  return sliceRight.hits.length - sliceLeft.hits.length;
                } else {
                  return sliceLeft.start - sliceRight.start;
                }
              });
              // select top N slices in content
              var upperBound = parseInt('1');
              if (upperBound >= 0) {
                slicesOfContent = slicesOfContent.slice(0, upperBound);
              }
              // highlight title and content
              function highlightKeyword(text, slice) {
                var result = '';
                var prevEnd = slice.start;
                slice.hits.forEach(function (hit) {
                  result += text.substring(prevEnd, hit.position);
                  var end = hit.position + hit.length;
                  result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                  prevEnd = end;
                });
                result += text.substring(prevEnd, slice.end);
                return result;
              }
              var resultItem = '';

              // if (slicesOfTitle.length != 0) {   resultItem += "<li><a target='_blank' href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>"; } else {   resultItem += "<li><a target='_blank' href='" +
              // articleUrl + "' class='search-result-title'>" + title + "</a>"; } slicesOfContent.forEach(function (slice) {   resultItem += "<a target='_blank' href='" + articleUrl + "'><p class=\"search-result\">" + highlightKeyword(content, slice) +
              // "...</p></a>"; }); resultItem += "</li>";

              if (slicesOfTitle.length != 0) {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</div><time class='search-result-date'>" + dateTime + "</time>";
              } else {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + title + "</div><time class='search-result-date'>" + dateTime + "</time>";
              }
              slicesOfContent.forEach(function (slice) {
                resultItem += "<p class=\"search-result-content\">" + highlightKeyword(content, slice) + "...</p>";
              });
              resultItem += "</div><div class='search-result-right'><img class='media-image' src='" + imgUrl + "' width='64px' height='48px'></img></div></a>";

              resultItems.push({item: resultItem, searchTextCount: searchTextCount, hitCount: hitCount, id: resultItems.length});
            }
          })
        };

        if (keywords.length === 1 && keywords[0] === "") {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else if (resultItems.length === 0) {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else {
          resultItems.sort(function (resultLeft, resultRight) {
            if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
              return resultRight.searchTextCount - resultLeft.searchTextCount;
            } else if (resultLeft.hitCount !== resultRight.hitCount) {
              return resultRight.hitCount - resultLeft.hitCount;
            } else {
              return resultRight.id - resultLeft.id;
            }
          });
          var searchResultList = '<div class=\"search-result-list\">';
          resultItems.forEach(function (result) {
            searchResultList += result.item;
          })
          searchResultList += "</div>";
          resultContent.innerHTML = searchResultList;
        }
      }
      if ('auto' === 'auto') {
        input.addEventListener('input', inputEventFunction);
      } else {
        $('.search-icon').click(inputEventFunction);
        input.addEventListener('keypress', function (event) {
          if (event.keyCode === 13) {
            inputEventFunction();
          }
        });
      }
      // remove loading animation
      $('body').css('overflow', '');
      proceedsearch();
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function (e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc('local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function (e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 && $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

    document.addEventListener('mouseup', (e) => {
      var _con = document.querySelector(".local-search-content");
      if (_con) {
        if (!_con.contains(e.target)) {
          onPopupClose();
        }
      }
    });
  </script>


		
	<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
